package com.pdg.mcplugin.questfor.dataproviders;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.bukkit.entity.Player;

import com.pdg.mcplugin.common.baseclasses.DataProviderBase;
import com.pdg.mcplugin.common.baseclasses.TableProviderBase;
import com.pdg.mcplugin.questfor.QuestFor;

public class QuestTableProvider extends TableProviderBase<QuestFor,DataProvider,QuestKey,QuestInstance> {
	private static final String TABLE_NAME = "quest_instances";
	private static final String DB_RETRIEVE_QUEST_INSTANCES_FOR_PLAYER_AND_WORLD = "SELECT `"+QuestKey.FIELD_QUEST+"`,`"+QuestInstance.FIELD_LEVEL+"`,`"+QuestInstance.FIELD_STATUS+"` FROM `"+TABLE_NAME+"` WHERE `"+QuestKey.FIELD_PLAYER+"`='%s' AND `"+QuestKey.FIELD_WORLD+"`='%s';";
	private static final String ERROR_COULD_NOT_RETRIEVE_QUEST_INSTANCES_FOR_PLAYER = "Could not retrieve quest instances for player!";

	public QuestTableProvider(DataProvider theDataProvider) {
		super(theDataProvider, TABLE_NAME, QuestKey.defaultInstance(), QuestInstance.defaultInstance());
	}

	public void updateOrCreate(QuestKey theKey, QuestInstance theInstance) {
		if(!update(theKey,theInstance)){
			create(theKey,theInstance);
		}
	}
	
	public List<PlayerQuestInstance> getQuestInstancesForPlayer(Player thePlayer) {
		if(!this.getDataProvider().doesTableExist(TABLE_NAME)) return null;
		try{
			//create a statement to check for inventory table
			Statement statement = getDataProvider().getConnection().createStatement();
			String theQuery = String.format(DB_RETRIEVE_QUEST_INSTANCES_FOR_PLAYER_AND_WORLD,
				DataProviderBase.sqlSafeString(thePlayer.getName()),
				DataProviderBase.sqlSafeString(thePlayer.getWorld().getName()));
			ResultSet result = statement.executeQuery(theQuery);
			List<PlayerQuestInstance> theResult = new ArrayList<PlayerQuestInstance>();
			while(result.next()){
				PlayerQuestInstance theQuest = new PlayerQuestInstance(result.getString(QuestKey.FIELD_QUEST),result.getInt(QuestInstance.FIELD_LEVEL), QuestStatus.valueOf(result.getString(QuestInstance.FIELD_STATUS))); 
				theResult.add(theQuest);
			}
			return theResult;
		}catch(Exception e){
			//an error has occurred
			getLogger().severe(getPlugin().formatMessage(ERROR_COULD_NOT_RETRIEVE_QUEST_INSTANCES_FOR_PLAYER));
			e.printStackTrace();
		}
		return null;
	}
}
